#include <stdio.h>
#include <fcntl.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include <string.h>

#include "hiir.h"


int ir_fd = 0;

int ir_open(void)
{
	ir_fd = open("/dev/"HIIR_DEVICE_NAME, O_RDWR);
	if (ir_fd < 0)
	{
		 printf("ERROR:can not open %s device. read return %d\n", HIIR_DEVICE_NAME, ir_fd);
		 return ir_fd;
	}
	
	return ir_fd;
}

int ir_close(void)
{
	if (ir_fd > 0)
	{
		close(ir_fd);
		ir_fd = 0;
	}

	return 0;
}

int ir_read(void)
{
	int res, count;
	irkey_info_s rcv_irkey_info[1];
	unsigned long vlaue_true = 0;

    struct timeval timeout;
    int nfds = ir_fd + 1;
    fd_set readfds;
    int select_ret;

    FD_ZERO( &readfds );
    FD_SET( ir_fd, &readfds );

    // Wait a second
    timeout.tv_sec = 0;
    timeout.tv_usec = 50000;

    while ( ( select_ret = select( nfds, &readfds, NULL, NULL, &timeout ) ) > 0 )
    {
        if ( FD_ISSET(ir_fd, &readfds) )
        {
            res = read(ir_fd, rcv_irkey_info, sizeof(rcv_irkey_info));
            count = res / sizeof(irkey_info_s);
            if( (res > 0) && (res<=sizeof(rcv_irkey_info)) )
            {
                if ( rcv_irkey_info[0].irkey_state_code == 1 )
                {
                    vlaue_true = rcv_irkey_info[0].irkey_datal;
                }
                else
                {
                    return -1;
                }
            }
            else
            {
                return -1;
            }
            
            return vlaue_true;
        }
        
        FD_ZERO( &readfds );
        FD_SET( ir_fd, &readfds );
        timeout.tv_sec = 0;
        timeout.tv_usec = 50000;
    }
	
    return -1;
}

/*
int main()
{
    ir_open();
    while (1)
    {
        ir_read();
    }
    ir_close();
	return 0;
}
*/
